package org.zezs.sync.mongo.plugs.idcard;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import jdk.nashorn.api.scripting.NashornScriptEngine;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zezs.sync.mongo.Constants;
import org.zezs.sync.mongo.config.mongo.MongoUtil;
import org.zezs.sync.mongo.plugs.Plug;

import javax.script.ScriptException;
import java.util.HashMap;
import java.util.Map;

public class IdcardLocationCache  extends Plug {
	public static Logger logger = LoggerFactory.getLogger(IdcardLocationCache.class);
	static Map<String, ProvinceCode> province = new HashMap<>();
	public static  Map<String, ProvinceCode> getProvinceCityTree() {
		synchronized (province){
			if(province.isEmpty()){
				logger.info("初始身份证定位");
				MongoCollection<Document> collection = MongoUtil.getMongoDb("paramConfig").getCollection("identity_province");
				FindIterable<Document> documents = collection.find();
				MongoCursor<Document> iterator = documents.iterator();
				Map<Integer, ProvinceCode> idProvince = new HashMap<>();

				while (iterator.hasNext()){
					Document next = iterator.next();
					ProvinceCode provinceCode = JSON.parseObject(next.toJson(), ProvinceCode.class);

					idProvince.put(provinceCode.getId(), provinceCode);
					province.put(provinceCode.getProvince_code(), provinceCode);
				}

				MongoCollection<Document> collection2 = MongoUtil.getMongoDb("paramConfig").getCollection("identity_city");
				MongoCursor<Document> documents2 = collection2.find().iterator();
				while (documents2.hasNext()){
					Document next = documents2.next();
					CityCode cityCode = JSON.parseObject(next.toJson(), CityCode.class);
					idProvince.get(cityCode.getP_id()).getCityMap().put(cityCode.getCity_code(), cityCode);
				}
				logger.info("初始身份证定位 结束 共计"+idProvince.size());
			}
		}

		return province;
	}
	@Override
	public void init(NashornScriptEngine engine) {
		try {
			this.jsFile="/plugs/idcard.js";
			initJs(engine);
			engine.invokeFunction("setIdcardProvince", IdcardLocationCache.getProvinceCityTree());
		} catch (ScriptException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

	}

}
